import 'dart:convert';

import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:schedule_self_client/api/schedule_self_server/task.dart';
import 'package:schedule_self_client/common/serializers.dart';

part 'task_list_resp_v2.g.dart';

abstract class TaskListRespV2
    implements Built<TaskListRespV2, TaskListRespV2Builder> {
  TaskListRespV2._();

  factory TaskListRespV2([void Function(TaskListRespV2Builder) updates]) =
      _$TaskListRespV2;

  bool get success;

  String? get errCode;

  String? get errMessage;

  BuiltList<Task> get data;

  String toJson() {
    return jsonEncode(
        serializers.serializeWith(TaskListRespV2.serializer, this));
  }

  static TaskListRespV2? fromJson(String jsonString) {
    return serializers.deserializeWith(
        TaskListRespV2.serializer, jsonDecode(jsonString));
  }

  static Serializer<TaskListRespV2> get serializer =>
      _$taskListRespV2Serializer;

  List<Task> getIncompleteTasks() {
    return data.where((task) => !task.isComplete()).toList()
      ..sort((a, b) => a.startTime.compareTo(b.startTime));
  }

  List<Task> getCompleteTasks() {
    return data
        .where((task) => task.isComplete() && task.completeTime != null)
        .toList()
      ..sort((a, b) {
        if (a.completeTime == null || b.completeTime == null) {
          return 0;
        }
        return b.completeTime!.compareTo(a.completeTime!);
      });
  }
}
